<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Db;

class Tool extends AdminBase
{
    public function index()
    {
        return view('');
    }

    public function makeKeywords(){
        if( $this->request->isPost() ){
            $param = $this->request->param();
            if(!empty($param)){
                $objPHPExcel = new \PHPExcel();
                $sheetindex =0;
                if(!empty($param['xiangmu'])){
                    $this->makeKeywordsExport1($param['xiangmu'],$objPHPExcel,$sheetindex);
                    $sheetindex++;
                }
                if(!empty($param['dalei'])){
                    $this->makeKeywordsExport2($param['dalei'],$objPHPExcel,$sheetindex);
                    $sheetindex++;
                }
                if(!empty($param['xiaolei'])){
                    $this->makeKeywordsExport3($param['xiaolei'],$objPHPExcel,$sheetindex);
                    $sheetindex++;
                }
                $objPHPExcel->removeSheetByIndex($sheetindex);
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="关键词.xlsx"');
                header('Cache-Control: no-cache');
                $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
                $objWriter->save('php://output');
            }
            
        }
        return view('');
    }

    private function makeKeywordsExport1($data,$objPHPExcel,$sheetindex){
        $objPHPExcel->createSheet();
        $objSheet = $objPHPExcel->setActiveSheetIndex($sheetindex);
        $objSheet->getColumnDimension('A')->setWidth(15);
        $objSheet->getColumnDimension('B')->setWidth(15);
        $objSheet->getColumnDimension('C')->setWidth(15);
        $objSheet->getColumnDimension('D')->setWidth(30);
        $objSheet->setTitle('项目');
        $objSheet->setCellValue('A1','大类')->setCellValue('B1','小类')->setCellValue('C1','项目')->setCellValue('D1','关键词');
        $list = Db::name('data_project')->field('title,typeid,parent_typeid')->select()->toArray();
        $index = 2;
        foreach($list as $row){
            $dalei = get_typename($row['parent_typeid']);
            $xiaolei = get_typename($row['typeid']);
            foreach($data as $v){
                $v = str_replace('{项目名称}',$row['title'],$v);
                $objSheet->setCellValue('A'.$index,$dalei)->setCellValue('B'.$index,$xiaolei)->setCellValue('C'.$index,$row['title'])->setCellValue('D'.$index,$v);
                $index++;
            }
        }
    }

    private function makeKeywordsExport2($data,$objPHPExcel,$sheetindex){
        $objPHPExcel->createSheet();
        $objSheet = $objPHPExcel->setActiveSheetIndex($sheetindex);
        $objSheet->getColumnDimension('A')->setWidth(15);
        $objSheet->getColumnDimension('B')->setWidth(15);
        $objSheet->getColumnDimension('C')->setWidth(15);
        $objSheet->getColumnDimension('D')->setWidth(30);
        $objSheet->setTitle('大类');
        $objSheet->setCellValue('A1','大类')->setCellValue('B1','小类')->setCellValue('C1','项目')->setCellValue('D1','关键词');
        $list = Db::name('data_type')->field('title')->where('level',1)->select()->toArray();
        $index = 2;
        foreach($list as $row){
            foreach($data as $v){
                $v = str_replace('{大类}',$row['title'],$v);
                $objSheet->setCellValue('A'.$index,$row['title'])->setCellValue('B'.$index,'')->setCellValue('C'.$index,'')->setCellValue('D'.$index,$v);
                $index++;
            }
        }
    }

    private function makeKeywordsExport3($data,$objPHPExcel,$sheetindex){
        $objPHPExcel->createSheet();
        $objSheet = $objPHPExcel->setActiveSheetIndex($sheetindex);
        $objSheet->getColumnDimension('A')->setWidth(15);
        $objSheet->getColumnDimension('B')->setWidth(15);
        $objSheet->getColumnDimension('C')->setWidth(15);
        $objSheet->getColumnDimension('D')->setWidth(30);
        $objSheet->setTitle('小类');
        $objSheet->setCellValue('A1','大类')->setCellValue('B1','小类')->setCellValue('C1','项目')->setCellValue('D1','关键词');
        $list = Db::name('data_type')->field('title,pid')->where('level',2)->select()->toArray();
        $index = 2;
        foreach($list as $row){
            $dalei = get_typename($row['pid']);
            foreach($data as $v){
                $v = str_replace('{小类}',$row['title'],$v);
                $objSheet->setCellValue('A'.$index,$dalei)->setCellValue('B'.$index,$row['title'])->setCellValue('C'.$index,'')->setCellValue('D'.$index,$v);
                $index++;
            }
        }
    }

    public function viewMake(){
        if( $this->request->isPost() ) {
            $param = $this->request->param();
            $dalei = get_typename($param['parent_typeid']);
            $xiaolei = get_typename($param['typeid']);
            $xiangmu = $param['project'];

            $data['tiaojian'] = $this->getChip(1,$xiangmu,$dalei,$xiaolei);
            $data['youshi'] = $this->getChip(2,$xiangmu,$dalei,$xiaolei);
            $data['liucheng'] = $this->getChip(3,$xiangmu,$dalei,$xiaolei);
            $data['zhichi'] = $this->getChip(4,$xiangmu,$dalei,$xiaolei);

            $make = new \app\common\lib\MakeTable();
            $table = $make->run($dalei);

            $data['cost'] = $table['cost'];
            $data['profit'] = $table['profit'];
        }
        $parent_typelist = Db::name('data_type')->where('level',1)->select()->toArray();
        if($param['parent_typeid']){
            $typelist = Db::name('data_type')->where([
                'level' => 2,
                'pid' => $param['parent_typeid']
            ])->select()->toArray();
        }
        return view('',['parent_typelist'=>$parent_typelist,'typelist'=>$typelist,'data'=>$data,'param'=>$param]);
    }

    public function exportProject()
    {
        if( $this->request->isPost() ) {
            $file = request()->file('file');
            if(empty($file)){
                return json(['status'=>'0','msg'=>'请上传文件!']);
            }
            $savename = \think\facade\Filesystem::putFileAs( 'excel', $file, 'exportProject.xlsx');
            $filePath = \think\facade\Filesystem::path($savename);

            if(!file_exists($filePath)){
                return json(['status'=>'0','msg'=>'文件不存在!']);
            }

            $input = $this->inputProject($filePath);
            
            $objPHPExcel = new \PHPExcel();
            $objSheet = $objPHPExcel->getActiveSheet();
            $objSheet->getColumnDimension('A')->setWidth(15);
            $objSheet->getColumnDimension('B')->setWidth(15);
            $objSheet->getColumnDimension('C')->setWidth(15);
            $objSheet->getColumnDimension('D')->setWidth(15);
            $objSheet->getColumnDimension('E')->setWidth(15);
            $objSheet->getColumnDimension('F')->setWidth(30);
            $objSheet->getColumnDimension('G')->setWidth(30);
            $objSheet->getColumnDimension('H')->setWidth(30);
            $objSheet->getColumnDimension('I')->setWidth(30);
            $objSheet->getColumnDimension('J')->setWidth(30);
            $objSheet->getColumnDimension('K')->setWidth(30);
            $objSheet->getColumnDimension('L')->setWidth(30);

            $objSheet->setTitle('第1页');
            $objSheet->setCellValue('A1','大类')->setCellValue('B1','小类')->setCellValue('C1','项目')->setCellValue('D1','公司名称')->setCellValue('E1','公司成立时间')->setCellValue('F1','公司地址')->setCellValue('G1','加盟条件')->setCellValue('H1','加盟优势')->setCellValue('I1','加盟支持')->setCellValue('J1','加盟流程')->setCellValue('K1','费用表')->setCellValue('L1','利润表');

            $make = new \app\common\lib\MakeTable();
            $index = 2;
            foreach($input as $v){
                $tiaojian = $this->getChip(1,$v['xiangmu'],$v['dalei'],$v['xiaolei']);
                $youshi = $this->getChip(2,$v['xiangmu'],$v['dalei'],$v['xiaolei']);
                $liucheng = $this->getChip(3,$v['xiangmu'],$v['dalei'],$v['xiaolei']);
                $zhichi = $this->getChip(4,$v['xiangmu'],$v['dalei'],$v['xiaolei']);

                $table = $make->run($v['dalei']);

                $com = DB::name('data_company')->where('title',$v['gongsi'])->find();
                if(empty($com)){
                    $com = apiGetCom($v['gongsi']);
                    $com = json_decode($com,true);
                    if(!empty($com['result'])){
                        $com = $com['result'];
                        $com['title'] = $v['gongsi']; 
                        Db::name('data_company')->insert($com);
                    }
                }
                
                $objSheet->setCellValue('A'.$index,$v['dalei'])->setCellValue('B'.$index,$v['xiaolei'])->setCellValue('C'.$index,$v['xiangmu'])->setCellValue('D'.$index,$v['gongsi'])->setCellValue('E'.$index,$com['regDate'])->setCellValue('F'.$index,$com['address'])->setCellValue('G'.$index,$tiaojian)->setCellValue('H'.$index,$youshi)->setCellValue('I'.$index,$zhichi)->setCellValue('J'.$index,$liucheng)->setCellValue('K'.$index,$table['cost'])->setCellValue('L'.$index,$table['profit']);
                $index++;
            }

            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="数据.xlsx"');
            header('Cache-Control: no-cache');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
            $objWriter->save('php://output');
        }
        return view('');
    }

    private function inputProject($filePath){
        $input = [];
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)) {
                return null;
            }
        }

        $PHPExcel = $PHPReader->load($filePath);
        $currentSheet = $PHPExcel->getSheet(0);
        //$allColumn = $currentSheet->getHighestColumn();
        $allRow = $currentSheet->getHighestRow();

        $limitNum = 10;
        $limitPage = ceil($allRow / $limitNum);
        for($i=0;$i<$limitPage;$i++){
            $limitIndex = $i * $limitNum;
            $limitEnd = $limitIndex + $limitNum;
            if($i == 0){
                $limitIndex = 2;
            }
            if($limitEnd >= $allRow){
                $limitEnd = $allRow+1;
            }
            for($currentRow = $limitIndex; $currentRow < $limitEnd; $currentRow++) {
                $arr['dalei'] = $currentSheet->getCell('A'.$currentRow)->getValue();
                $arr['xiaolei'] = $currentSheet->getCell('B'.$currentRow)->getValue();
                $arr['xiangmu'] = $currentSheet->getCell('C'.$currentRow)->getValue();
                $arr['gongsi'] = $currentSheet->getCell('D'.$currentRow)->getValue();
                if(empty($arr['xiangmu'])){
                    break;
                }
                $r = Db::name('data_project')->where([
                    'title' => $arr['xiangmu']
                ])->find();
                if(empty($r)){
                    $parent_typeid = get_typeid($arr['dalei'],1);
                    $typeid = get_typeid($arr['xiaolei'],2);
                    if(empty($parent_typeid) || empty($typeid)){
                        continue;
                    }
                    $top_typeid =  get_typepid($parent_typeid);
                    Db::name('data_project')->insert([
                        'title' => $arr['xiangmu'],
                        'typeid' => $typeid,
                        'parent_typeid' => $parent_typeid,
                        'top_typeid' => $top_typeid,
                        'alias' => $arr['xiangmu'],
                        'company' => $arr['gongsi']
                    ]);
                }
                $input[] = $arr;  
            }
        }
        return $input;
    }

    //获取 条件 优势 流程
    private function getChip($position,$xiangmu,$dalei,$xiaolei){
        $str = '';
        $data = $this->chip($position);
        if(!empty($data)){
            $num = 0;
            $count = count($data);
            foreach ($data as $v) {
                $num++;
                if($num==$count){
                    $v .= '。';
                }else{
                    $v .= '；';
                }
                $v = str_replace('www', '17商机网', $v);
                $v = str_replace('xxx', $xiangmu, $v);
                $v = str_replace('dalei', $dalei, $v);
                $v = str_replace('xiaolei', $xiaolei, $v);
                $str .= '<p>'.$num.'.'.$v.'</p>';
            }
        }
        return $str;
    }

    //条件 优势 流程 支持
    private function chip($position)
    {
        if( empty($position) ){
            return null;
        }
        
        $data = [];
        $model = new \app\common\model\DataContentChip();
        if($position==1 || $position==2){
            $num = mt_rand(5,8);
            $res = $model->getDataByPosition($position, $num); 
            $exist = false;
            foreach($res as $v){
                if(strpos($v['title'],'首先') !== false){
                    array_unshift($data,$v['title']);
                }elseif(strpos($v['title'],'岁') !== false){
                    if(!$exist){
                        array_unshift($data,$v['title']);
                        $exist = true; 
                    }
                }else{
                    array_push($data,$v['title']);
                }
            }
        }elseif($position==3){
            $temp = Db::name('data_content_chip_template')->where('position',$position)->orderRand()->find();
            $arr = explode(',',$temp['value']);
            foreach($arr as $v){
                $res = $model->getDataByPositionOne($position, $v);
                if($res != null){
                    $data[] = $res->title;
                }
            }
        }elseif($position==4){
            $temp = Db::name('data_content_chip_template')->where('position',$position)->orderRand()->find();
            if(!empty($temp['step'])){
                $res = $model->getDataByPosition($position, $temp['step']); 
                foreach($res as $v){
                    $data[] = $v['title'];
                }
            }
        }else{
            return null;
        }
        return $data;
    }

    //获取企业信息
    // private function getEnterprise($kw){
    //     if( empty($kw) ){
    //         return null;
    //     }
        
    //     $headers = array(
    //         'Cookie: BAIDUID=52E31DFFA514C24FFA4B0B8C7DA45D61:FG=1;'
    //     );

    //     $domain = "https://aiqicha.baidu.com";
    //     $url = $domain."/s?q=".$kw;
    //     $output = http_request($url,$headers);
    //     $sub = '"resultList":[{"pid":"';
    //     $pos = strpos($output,$sub);
    //     if(empty($pos)){
    //         return null;
    //     }
    //     $pid = substr($output,$pos+strlen($sub),14);
    //     //基本信息
    //     $url = $domain."/detail/basicAjax?pid=".$pid;
    //     $json = http_request($url,$headers);
    //     $arr = json_decode($json,true);
    //     $data['entName'] = $arr['data']['entName'];
    //     $data['regAddr'] = $arr['data']['regAddr'];
    //     $data['startDate'] = $arr['data']['startDate']; 

    //     return $data;
    // }

}
